/* eslint-disable camelcase */
'use strict'
const path = require('path')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin') // 去掉注释
const env = process.env // 环境变量

function resolve(dir) {
  return path.join(__dirname, dir)
}

// cdn预加载使用
const externals = {
  'vue': 'Vue',
  'vue-router': 'VueRouter',
  'vuex': 'Vuex',
  'element-ui': 'ELEMENT',
  'axios': 'axios'
}

const cdn = {
  // 开发环境
  dev: {
    css: [
      // 阿里图标字体
      'https://at.alicdn.com/t/font_2412290_ux01hi88tt.css'
    ],
    js: []
  },
  // 生产环境
  build: {
    css: [
      // 阿里图标字体
      'https://at.alicdn.com/t/font_2412290_ux01hi88tt.css',
      'https://unpkg.com/element-ui/lib/theme-chalk/index.css'
    ],
    js: [
      'https://cdn.jsdelivr.net/npm/vue@2.6.12',
      'https://unpkg.com/vue-router/dist/vue-router.js',
      'https://unpkg.com/vuex',
      'https://unpkg.com/element-ui/lib/index.js',
      'https://unpkg.com/axios/dist/axios.min.js'
    ]
  }
}

module.exports = {
  lintOnSave: false, // 关闭eslint
  publicPath: '/',
  outputDir: env.VUE_APP_MODE,
  chainWebpack: config => {
    config.resolve.alias.set('@', resolve('src'))
    config.plugin('html').tap(args => {
      if (env.NODE_ENV === 'production') {
        args[0].cdn = cdn.build
      }
      if (env.NODE_ENV === 'development') {
        args[0].cdn = cdn.dev
      }
      return args
    })
  },
  configureWebpack: config => {
    const plugins = []
    if (env.NODE_ENV === 'production') {
      plugins.push(
        new UglifyJsPlugin({
          uglifyOptions: {
            output: {
              comments: false // 去掉注释
            },
            warnings: false,
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log'] // 移除console
            }
          }
        })
      )
      // 开启分离js
      config.optimization = {
        runtimeChunk: 'single',
        splitChunks: {
          chunks: 'all',
          maxInitialRequests: Infinity,
          minSize: 1000 * 60,
          cacheGroups: {
            vendor: {
              test: /[\\/]node_modules[\\/]/,
              name(module) {
                // 排除node_modules 然后吧 @ 替换为空 ,考虑到服务器的兼容
                const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
                return `npm.${packageName.replace('@', '')}`
              }
            }
          }
        }
      }
      // 打包时npm包转CDN
      config.externals = externals
    }
    return { plugins }
  }
}
